import 'package:encrypt/encrypt.dart';

class YLAESEncrypt {
  // 单例
  static YLAESEncrypt get instance => _instanceBase();
  static YLAESEncrypt? _manager;
  static YLAESEncrypt _instanceBase() {
    _manager ??= YLAESEncrypt();
    return _manager!;
  }

  Encrypter? _encrypter;
  IV? _iv;
  String encrypter(String value) {
    if (_encrypter != null && value.isNotEmpty) {
      return _encrypter!.encrypt(value, iv: _iv).base64;
    }
    return value;
  }

  String decrypter(String value) {
    if (_encrypter != null && value.isNotEmpty) {
      return _encrypter!.decrypt64(value, iv: _iv);
    }
    return value;
  }

  String encrypter16(String value) {
    if (_encrypter != null && value.isNotEmpty) {
      return _encrypter!.encrypt(value, iv: _iv).base16;
    }
    return value;
  }

  String decrypter16(String value) {
    if (_encrypter != null && value.isNotEmpty) {
      return _encrypter!.decrypt16(value, iv: _iv);
    }
    return value;
  }

  setEncryptKey({
    String keystr = 'Bx!y^6c9n=aRDv@Q',
    String ivstr = 'ow3tmfo490q7j1rw',
  }) async {
    final key = Key.fromUtf8(keystr);
    _iv = IV.fromUtf8(ivstr);
    _encrypter = Encrypter(AES(key));
  }
}

class YLAESCBCEncrypt {
  // 单例
  static YLAESCBCEncrypt get instance => _instanceBase();
  static YLAESCBCEncrypt? _manager;
  static YLAESCBCEncrypt _instanceBase() {
    _manager ??= YLAESCBCEncrypt();
    return _manager!;
  }

  Encrypter? _encrypter;
  IV? _iv;
  String encrypter(String value) {
    if (_encrypter != null && value.isNotEmpty) {
      return _encrypter!.encrypt(value, iv: _iv).base64;
    }
    return value;
  }

  String decrypter(String value) {
    if (_encrypter != null && value.isNotEmpty) {
      return _encrypter!.decrypt64(value, iv: _iv);
    }
    return value;
  }

  String encrypter16(String value) {
    if (_encrypter != null && value.isNotEmpty) {
      return _encrypter!.encrypt(value, iv: _iv).base16;
    }
    return value;
  }

  String decrypter16(String value) {
    if (_encrypter != null && value.isNotEmpty) {
      return _encrypter!.decrypt16(value, iv: _iv);
    }
    return value;
  }

  setEncryptKey({
    String keystr = 'Bx!y^6c9n=aRDv@Q',
    String ivstr = 'ow3tmfo490q7j1rw',
  }) async {
    final key = Key.fromUtf8(keystr);
    _iv = IV.fromUtf8(ivstr);
    _encrypter = Encrypter(AES(key, mode: AESMode.cbc));
  }
}
